package com.clstu.homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);//在8888端口监听数据
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //接收端等待接受数据
        System.out.println("接收端等待在 8888端口 接收数据");
        socket.receive(packet);//接受数据

        int readLen = packet.getLength();//拆包
        byte[] data = packet.getData();
        String s = new String(data,0,readLen);
        String answer = null;
        if(s.equals("四大名著是什么?")){
            answer = "分别是<红楼梦>,<水浒传>,<三国演义>,<西游记>";
        }else {
            answer = "what";
        }
        byte[] data1 = answer.getBytes();//数据封包 到DatagramPacket对象    //指定对面主机和端口号
        DatagramPacket packet1 = new DatagramPacket(data1, data1.length, InetAddress.getByName("192.168.1.5"), 9999);
        socket.send(packet1);//发送

        socket.close();//关闭资源

    }
}
